import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import {
  VueAxios
} from './axios'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
import {
  Modal,
  notification
} from 'ant-design-vue'
/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
// let apiBaseUrl = 'http://192.168.1.77:8089/lampblack-boot/web'
let apiBaseUrl = process.env.VUE_APP_BASE_API
// 创建 axios 实例
const service = axios.create({
  //baseURL: '/jeecg-boot',
  baseURL: apiBaseUrl, // api base_url
  timeout: 20000, // 请求超时时间
})
let Forbidden = false // 标记接口权限
let isRefreshing = false // 标记是否正在刷新 token
let requests = [] // 存储待重发请求的数组

const err = (error) => {
  if (error.response) {
    let data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    console.log('------异常响应------', token)
    console.log('------异常响应------', error.response.status)
    switch (error.response.status) {
      case 403:
        if (Forbidden == false) {
          Forbidden = true
          notification.error({
            message: '系统提示',
            description: '没有权限访问',
            duration: 4,
          })
          setTimeout(() => {
            Forbidden = false
          }, 3000)
        }
        break
      case 500:
        console.log('------error.response------', error.response)
        notification.error({
          message: '系统提示',
          description: '服务器内部异常',
          duration: 4,
        })
        break
      case 401:
        if (!error.config.url.includes('/refresh_token')) {
          const { config } = error
          config.baseURL = ''
          if (!isRefreshing) {
            isRefreshing = true
            store.dispatch('getRefreshToken').then((res) => {
              // window.location.reload()
              // 无感刷新部分页面不能正常加载
              requests.forEach((cb) => cb())
              // console.log(requests, '请求的列表')
              requests = [] // 重新请求完清空
              service(config)
              return service(config)
            }).catch(error => {
              console.log(error, 'Error getting refresh token')
              if (error.code !== 200) {
                Modal.error({
                  title: '登录已过期',
                  content: '很抱歉，登录已过期，请重新登录',
                  okText: '重新登录',
                  mask: false,
                  onOk: () => {
                    store.dispatch('Logout').then(() => {
                      Vue.ls.remove(ACCESS_TOKEN)
                      window.location.reload()
                    })
                  },
                })
              }
            }).finally(() => {
              isRefreshing = false
            })
          } else {
            // 返回未执行 resolve 的 Promise
            return new Promise(resolve => {
              // 用函数形式将 resolve 存入，等待刷新后再执行
              requests.push(token => {
                resolve(service(config))
              })
            })
          }
        }
        break
      case 404:
        notification.error({
          message: '系统提示',
          description: '很抱歉，资源未找到!',
          duration: 4,
        })
        break
      case 504:
        notification.error({
          message: '系统提示',
          description: '网络超时',
        })
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4,
        })
        break
    }

  } else if (error.message) {
    if (error.message.includes('timeout')) {
      notification.error({
        message: '系统提示',
        description: '网络超时',
      })
    } else {
      notification.error({
        message: '系统提示',
        description: error.message,
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (token) {
      config.headers['X-WEB-TOKEN'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use((response) => {
  if (response.data.code && response.data.code !== 200) {
    notification.error({
      message: '系统提示',
      description: response.data.message,
      duration: 4,
    })
    return Promise.reject(response.data)
  } else {
    return response.data
  }
}, err)

const installer = {
  vm: {},
  install (Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  },
}

export {
  installer as VueAxios, service as axios
}